<template>
	<div class="system-schoolManager-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="schoolManagerDialogFormRef" :model="state.ruleForm" size="default" label-width="90px" :rules="rules">
				<el-row :gutter="35">
					<el-col class="mb20">
						<el-form-item label="老师手机号" prop="username" label-width="auto">
							<el-select
								v-model="state.ruleForm.id"
								filterable
								remote
								reserve-keyword
								placeholder="请输入老师手机号进行搜索"
								remote-show-suffix
								:remote-method="remoteMethod"
								:loading="state.loading"
								style="width: 500px"
								@change="onChange"
								:disabled="state.dialog.type === 'edit'"
							>
								<el-option v-for="item in state.options" :key="item.id" :label="item.nickName" :value="item.id">
									<span style="float: left">{{ item.username }}</span>
									<span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">{{ item.nickName }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="权限选择" prop="userRoles" label-width="auto">
							<el-checkbox-group v-model="state.ruleForm.userRoles">
								<el-checkbox label="普通教师" value="TEACHER" disabled />
								<el-checkbox label="家长" value="PARENT" disabled />
								<el-checkbox label="学校管理员" value="SCHOOL_MANAGER" />
								<el-checkbox label="教师管理员" value="TEACHER_MANAGER" />
							</el-checkbox-group>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(schoolManagerDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="schoolManagerDialog">
import { reactive, ref} from 'vue';
import {userApi} from "/@/api/user";
import {ElMessage, FormInstance, FormRules} from 'element-plus'
const {savePermission,teacherListByPage} = userApi();
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

const rules = reactive<FormRules<RowManagerUserType>>({
  username: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    //{ min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  nickName: [
    {
      required: true,
      message: '请输入姓名',
      trigger: 'blur',
    },
  ],


})

// 定义变量内容
const schoolManagerDialogFormRef = ref();
const state = reactive({
	ruleForm: {
    id: '',
    username: '',
    orgId: '',
    orgName: '',
    nickName: '',
    userType: 1,
    gender: 0,
    userMobile: '',
    idType: '',
    userIdCardNumber: '',
    userRole: '',
    userRoles: [''],
    nth: '',
    gmtCreate: '',
    isDelete: 0,
    gmtModified: '',
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
  loading:false,
  options: [
    {
      id:'',
      nickName:'',
      username:'',
      userRoles: [''],
    }
  ],
});

// 打开弹窗
const openDialog = (type: string, row: RowManagerUserType) => {
  state.dialog.type = type;
	if (type === 'edit') {
		state.ruleForm = row;
    state.options=[
      {
        id:row.id,
        nickName:row.nickName,
        username:row.username,
        userRoles: row.userRoles,
      }
    ]
		state.dialog.title = '修改老师权限';
		state.dialog.submitTxt = '修 改';
	} else {
		state.dialog.title = '教师赋权';
		state.dialog.submitTxt = '确 定';
    clearForm();
	}
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
// const onSubmit = () => {
// 	closeDialog();
// 	emit('refresh');
// 	// if (state.dialog.type === 'add') { }
// };
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      state.ruleForm.userType = 1;
      const res = await savePermission({
        id: state.ruleForm.id,
        userRoles: state.ruleForm.userRoles,
      })
      if (res.status === 200) {
        ElMessage.success('更改成功');
        emit('refresh');
      }else{
        ElMessage.error('更改失败');
      }
      closeDialog();

    }
  })
}

const remoteMethod = async (query: string) => {
  if (query !== '') {
    state.loading = true;
    const res = await teacherListByPage({
      userName: query,
    })
    if (res.status === 200) {
      //console.log(res);
      state.options = res.data.records;
      state.loading = false;
    }
  }
}
const onChange = () => {
  const selectedOption = state.options.find(option => option.id === state.ruleForm.id);
  if (selectedOption) {
    state.ruleForm.username = selectedOption.username;
    state.ruleForm.nickName = selectedOption.nickName;
    state.ruleForm.userRoles = selectedOption.userRoles;
    // 可以根据需要更新其他字段
  }
}
const clearForm = () => {
  state.ruleForm = {
    id: '',
    username: '',
    orgId: '',
    orgName: '',
    nickName: '',
    userType: 1,
    gender: 0,
    userMobile: '',
    idType: '',
    userIdCardNumber: '',
    userRole: '',
    userRoles: [''],
    nth: '',
    gmtCreate: '',
    isDelete: 0,
    gmtModified: '',
  }
}
// 暴露变量
defineExpose({
	openDialog,
});
</script>
